/*
 * =====================================================================================
 *
 *       Filename:  thinFast.cpp
 *
 *    Description:  Thinning with LUT's
 *
 *        Version:  1.0
 *        Created:  26/07/12 11:21:09
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Moos Hueting (mh), mooshueting@gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include <iostream>
#include <cv.h>
#include <highgui.h>

#include "thinLUT.h"

using namespace std;
using namespace cv;

bool thinLUTOneIt(Mat *src) {
    Size s = src->size();
    short changed = 0;

    *src = *src / 255;

    Mat mask(s.width, s.height, CV_8UC1, Scalar(1));

    for (int i = 1; i < s.height - 1; i++) {
        for (int j = 1; j < s.width - 1; j++) {
            int index = 0;

            uchar* p = src->ptr<uchar>(i-1);
            index += p[j-1] + p[j]*2 + p[j+1]*4;

            p = src->ptr<uchar>(i);
            index += p[j-1]*8 + p[j]*16 + p[j+1]*32;

            p = src->ptr<uchar>(i+1);
            index += p[j-1]*64 + p[j]*128 + p[j+1]*256;

            changed += LUT_firstit[index] != src->ptr<uchar>(i)[j];
            src->ptr<uchar>(i)[j] = LUT_firstit[index];
        }
    }

/*     multiply(*src, mask, *src);
 * 
 *     mask = Mat(s.width, s.height, CV_8UC1, Scalar(1));
 */
    for (int i = 1; i < s.height - 1; i++) {
        for (int j = 1; j < s.width - 1; j++) {
            int index = 0;

            uchar* p = src->ptr<uchar>(i-1);
            index += p[j-1] + p[j]*2 + p[j+1]*4;

            p = src->ptr<uchar>(i);
            index += p[j-1]*8 + p[j]*16 + p[j+1]*32;

            p = src->ptr<uchar>(i+1);
            index += p[j-1]*64 + p[j]*128 + p[j+1]*256;

            changed += LUT_firstit[index] != src->ptr<uchar>(i)[j];
            src->ptr<uchar>(i)[j] = LUT_firstit[index];
        }
    }

 //   multiply(*src, mask, *src);

    *src = *src * 255;

    return (bool)changed;

}

Mat thinLUT(Mat src) {
    while (thinLUTOneIt(&src))
        ;

    return src;
}

